import { encryptedData } from '@/utils/utils';
import '@ant-design/compatible/assets/index.css';
import { Form, Input, message, Modal } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import React, { PureComponent } from 'react';
import { publicKey } from '../../../../public/global';
import { specicalChars, styleRequired } from '../../../support/constant/common.js';
import { validateContinuousChar } from '@/utils/validator';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 16 },
  },
};
const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  menu: state.menu,
  tenant: state.tenant,
});
class AddAdminModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      buttonLoading: false,
      preventBehavior: true, // 阻止浏览器默认填充
    };
  }

  timer: any = null;

  componentWillUnmount(): void {
    if(this.timer) {
      clearTimeout(this.timer)
    }
  }

  componentDidUpdate(prevProps: Readonly<any>, prevState: Readonly<any>, snapshot?: any): void {
    const { modalVisible } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
       // 阻止浏览器默认填充
       if(this.state.preventBehavior) {
        this.timer = setTimeout(() => {
          this.setState({
            preventBehavior: false,
          })
        }, 1000);
      }
    }
  }

  close = () => {
    const { closeModal } = this.props;
    closeModal();
    this.formRef.current?.resetFields();
    this.setState({
      buttonLoading: false,
      preventBehavior: true
    });
  };

  checkPwd = (rule: any, value: any, callback: any) => {
    const {
      menu: {
        pwdStrategy: { pwdStrategy, pwdStrategyDesc },
      },
    } = this.props;
    if (value) {
      const regex = new RegExp(pwdStrategy);
      if (!regex.test(value)) {
        return Promise.reject(`请输入正确的密码，${pwdStrategyDesc}`);
      }else if(/([\dA-Za-z])\1{3,}/.test(value)) {
        return Promise.reject('禁止密码设置4位连续相同的字符');
      } else if(validateContinuousChar(value)) {
        return Promise.reject('禁止密码设置4位连续递增，递减的数字或字母');
      } else if(specicalChars.some(char => value.toLowerCase().indexOf(char.toLowerCase()) > -1 )) {
        return Promise.reject('禁止密码设置4位1qaz，2wsx，3edc，dfm，admin，dftc，dfrd等简单字符');
      }
    } else {
      return Promise.reject('请输入密码');
    }
    return Promise.resolve();
  };

  checkRePwd = (rule: any, value: any, callback: any) => {
    const {
      menu: {
        pwdStrategy: { pwdStrategy, pwdStrategyDesc },
      },
    } = this.props;
    if (value) {
      const regex = new RegExp(pwdStrategy);
      if (!regex.test(value)) {
        return Promise.reject(`请输入正确的密码，${pwdStrategyDesc}`);
      }
    } else {
      return Promise.reject('请输入确认密码');
    }
    return Promise.resolve();
  };

  getLabel = (lable: any) => (
    <span>
      <span style={styleRequired}>* </span>
      {lable}
    </span>
  );

  ok = (values: any) => {
    const { dispatch, tenantCode, tenantSid, isSelectAll, refresAdmin } = this.props;
    this.setLoading(true);
    if (values.accountPwd !== values.confirmPwd) {
      message.error('两次密码输入不一致，请重新输入！');
      this.setLoading(false);
      return;
    }
    let obj: any = {};
    obj.accountName = values.accountName;
    obj.accountPwd = encryptedData(values.accountPwd, publicKey);
    dispatch({
      type: 'tenant/postObjWithRes',
      payload: {
        url: '/account/add',
        tenantCode: tenantCode,
        tenantSid: tenantSid,
        isSelectAll: isSelectAll,
        mail: values.mail,
        ...obj,
      },
      callback: (response: any) => {
        this.setLoading(false);
        if (response.statusCode === '0') {
          message.success('保存成功');
          this.close();
          refresAdmin();
        } 
      },
    });
  };

  setLoading = (flag: any) => {
    this.setState({
      buttonLoading: flag,
    });
  };

  submitForm = () => {
    this.formRef.current?.submit();
  };

  render() {
    const { modalVisible } = this.props;
    const { buttonLoading, preventBehavior } = this.state;
    return (
      <Modal
        title="新增管理员"
        open={modalVisible}
        onCancel={this.close}
        okText="保存"
        okButtonProps={{ size: 'small', loading: buttonLoading }}
        cancelButtonProps={{ size: 'small' }}
        onOk={this.submitForm}
        destroyOnClose
      >
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.ok}>
          <FormItem
            {...formItemLayout}
            label="登录账号"
            name="accountName"
            hasFeedback
            rules={[
              { required: true, message: '请输入登录账号' },
              // { pattern: /^[0-9a-zA-Z]*$/, message: '登录账号只能为字母和数字' }
            ]}
          >
            <Input maxLength={64} readOnly={preventBehavior} placeholder="请输入登录账号" />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="邮箱"
            name="mail"
            hasFeedback
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '邮箱格式错误' }, 
            ]}
          >
            <Input maxLength={64} readOnly={preventBehavior} placeholder="请输入邮箱" />
          </FormItem>
          <FormItem
            {...formItemLayout}
            name="accountPwd"
            label={this.getLabel('密码')}
            hasFeedback
            rules={[{ validator: this.checkPwd }]}
          >
            <Input.Password maxLength={50} readOnly={preventBehavior} placeholder="请输入密码" />
          </FormItem>
          <FormItem
            {...formItemLayout}
            name="confirmPwd"
            label={this.getLabel('确认密码')}
            dependencies={['accountPwd']}
            hasFeedback
            rules={[
              { validator: this.checkRePwd },
              ({ getFieldValue }) => {
                return {
                    validator(_, value) {
                      if (!value || getFieldValue('accountPwd') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不匹配！'));
                    },
                  }
                }
            ]}
          >
            <Input.Password maxLength={50} readOnly={preventBehavior} placeholder="请输入确认密码" />
          </FormItem>
        </Form>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(AddAdminModal);
